package com.sun.dream.fish.controller;

import com.sun.dream.fish.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * Description:  文件管理接口
 * Created By ljl on 2023/11/24.
 */
@RestController
public class FileManagerController {
    @Autowired
    IFileService fileService;

    @PostMapping(value = "/excel/upload")
    public ResponseEntity<String> excelUpload(@RequestPart("file") MultipartFile file, @RequestParam("newName") String newName) {
        if (file == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("请选择文件上传");
        }
        return fileService.storeExcelFile(file, newName) ? ResponseEntity.status(HttpStatus.OK).body("文件上传成功") : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
    }

    @PostMapping(value = "/excel/download")
    public ResponseEntity<FileSystemResource> excelDownload(@RequestParam(value = "fileName", required = false) String fileName) {
        FileSystemResource fileSystemResource;
        try {
            fileSystemResource = fileService.downloadExcelFile(fileName);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (fileSystemResource == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.parse("attachment; filename=" + fileSystemResource.getFilename()));
        return new ResponseEntity<>(fileSystemResource, headers, HttpStatus.OK);
    }
}
